package com.powerhua.privilege.web.action;

import com.powerhua.core.utils.CommonUtils;
import java.util.List;

import javax.servlet.ServletRequest;

import com.powerhua.privilege.PrivilegeUtils;
import com.powerhua.privilege.domain.Privilege;
import com.powerhua.privilege.web.action.convert.PrivilegeConverter;
import com.powerhua.support.web.HtmlBeanConverter;

public class PrivilegeAction implements ActionInterface {

    public String doAction(ServletRequest map) {
        String result = "";

        String action = CommonUtils.getStringFromReq(map, PrivilegeUtils
                .getPermissionParamProperty("Param.Action"));
        if (action.equals(PrivilegeUtils.getPermissionParamProperty("Action.Info"))) {
            Privilege pm = (Privilege) HtmlBeanConverter.getBeanFromHtml(Privilege.class, map);
            Privilege PermissionFromDb = getInfo(pm);
            result = PrivilegeConverter.getInfoScriptStr(PermissionFromDb);
        } else if (action.equals(PrivilegeUtils.getPermissionParamProperty("Action.List"))) {
            String start = CommonUtils.getStringFromReq(map, PrivilegeUtils
                    .getPermissionParamProperty("Param.Start"));
            String offset = CommonUtils.getStringFromReq(map, PrivilegeUtils
                    .getPermissionParamProperty("Param.Offset"));
            List list = getList(start, offset);
            result = PrivilegeConverter.getListScriptStr(list);
        }

        return result;
    }

    private Privilege getInfo(Privilege Permission) {
        List list = PrivilegeUtils.getPermissionManager().findPermissions(Permission, 0, 0);
        if (!(list.size() == 1)) {
            return null;
        } else {
            return (Privilege) list.get(0);
        }
    }

    private List getList(String start, String offset) {
        int intStart = Integer.parseInt(start);
        int intOffset = Integer.parseInt(offset);
        List list = PrivilegeUtils.getPermissionManager().findPermissions(null, intStart,
                intOffset);
        return list;
    }

}
